package config

import (
	"github.com/spf13/viper"
	"go.uber.org/zap"
	log "gobase/logger"
	"gobase/mysqlDB"
	"os"
	"strings"
)

type Config struct {
	MysqlDB      mysqlDB.DBConfig `yaml:"MysqlDB"`
	Redis        Redis            `yaml:"redis"`
	InfluxDB     influxdb         `yaml:"influxDB"`
	MsManager    MsManager        `yaml:"MsManager"`
	ConfigThrift ConfigThrift     `yaml:"ConfigThrift"`
	OpenApi      OpenApi          `yaml:"OpenApi"`
}

var config Config

func InitConfig() {

	var configPath string
	absPath, _ := os.Getwd()
	pathSlice := strings.Split(absPath, "gobase")
	if len(pathSlice) > 0 {
		configPath = pathSlice[0] + "/config"
	} else {
		var err error
		log.Error("获取配置路径失败", zap.Error(err))
		return
	}

	log.Debug("配置文件路径: ", zap.Any("configPath", configPath))
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(configPath)
	//viper.AddConfigPath("../")
	//viper.AddConfigPath("/configs")
	if err := viper.ReadInConfig(); err != nil {
		log.Error("读取配置失败", zap.Error(err))
		return
	}
	viper.SetEnvPrefix("Sentinel")
	viper.AutomaticEnv()
	if err := viper.Unmarshal(&config); err != nil {
		log.Error("解析配置失败", zap.Error(err))
		return
	}

	if config.MsManager.MaxCpuUsedPercent == 0 {
		config.MsManager.MaxCpuUsedPercent = 0.8
	}
	if config.MsManager.MaxMemUsedPercent == 0 {
		config.MsManager.MaxMemUsedPercent = 0.8
	}
}

func GetAll() Config {
	return config
}
